<template>
  <el-row class="form-inspect-plan" type="flex" justify="center">
    <el-col>
      <el-form label-width="120px" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
        <input type="hidden" v-model="editForm.id" />
        <el-form-item label="计划名称：" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" placeholder="同一个单位下的名称不要重复，可以带上单位名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="巡检标签：" prop="labelId">
          <el-select v-model="editForm.labelId" placeholder="请选择标签" filterable>
            <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <!-- <el-autocomplete
            v-model="editForm.tag"
            :fetch-suggestions="querySearch"
            placeholder="请选择或输入标签"
            clearable
            style="width:100%;"
          ></el-autocomplete>-->
          <p style="margin:10px 0 0;color:#999;line-height:16px;">提示：相同用途的巡检请使用相同的标签。系统会按照标签进行巡检的数据统计分析。</p>
        </el-form-item>
        <el-form-item class="formitem-point" prop="planPointsId" label="包含点位">
          <el-cascader
            ref="myCascader"
            v-model="editForm.planPointsId"
            :options="nodeOptions"
            :props="nodeProps"
            clearable
            style="width:100%;"
            @change="handleNodeChange"
          ></el-cascader>
          <div class="point-names" v-if="pointNames">原计划点位：{{pointNames}}</div>
          <p v-if="isCrossPlatfrom" style="color:red;">请注意，你已跨单位选择点位，请谨慎操作</p>
        </el-form-item>
        <el-form-item label="责任人：" prop="chargeManIds" v-loading="userLoading">
          <el-radio-group v-model="editForm.lliableType">
            <el-radio :label="1">组织</el-radio>
            <el-radio :label="2">人员</el-radio>
          </el-radio-group>
          <el-select
            v-if="editForm.lliableType==2"
            v-model="editForm.chargeManIds"
            placeholder="请选择人员"
            filterable
            multiple
            clearable
          >
            <el-option v-for="item in userList" :key="item.accountName" :label="item.name" :value="item.accountName"></el-option>
          </el-select>
          <template v-else>
            <el-input v-if="isCrossPlatfrom" :value="userinfo.org.name" readonly></el-input>
            <el-select v-else v-model="editForm.chargeManIds" placeholder="请选择组织" filterable multiple clearable>
              <el-option v-for="item in nodeOrgOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="startTimeStr" label="开始日期">
              <el-date-picker
                v-model="editForm.startTimeStr"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
                type="date"
                placeholder="请选择"
                :picker-options="pickerOptions"
                @change="handleStartDateChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="endTimeStr" label="结束日期">
              <el-date-picker
                v-model="editForm.endTimeStr"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
                type="date"
                placeholder="可不选"
                :picker-options="endDateOptions"
                @change="handleEndDateChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="巡检频率：">
          <el-radio-group v-model="editForm.examineRate">
            <el-radio :label="2">一天多次</el-radio>
            <el-radio :label="1">一天一次</el-radio>
            <el-radio :label="3">一周一次</el-radio>
            <el-radio :label="4">一月一次</el-radio>
            <el-radio :label="5">一季度一次</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-card>
            <template v-if="editForm.examineRate==2">
              <el-form-item v-for="(item,i) in inspectTimesList" :key="i" :label="'第'+(i+1)+'次巡检：'">
                <span class="my-picker-wrap">
                  <template v-if="i==0">
                    <el-button class="switch-today" type="text" disabled>当日</el-button>
                  </template>
                  <template v-else>
                    <el-dropdown @command="v=>{handleDayCommand(item,v,'startIsNextday')}">
                      <span class="el-dropdown-link">
                        <el-button type="text">{{item.startIsNextday?'次日':'当日'}}</el-button>
                        <i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="false">当日</el-dropdown-item>
                        <el-dropdown-item :command="true">次日</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                  <el-time-select
                    v-model="item.startTime"
                    placeholder="开始时间"
                    value-format="HH:mm"
                    format="HH:mm"
                    :clearable="false"
                    :picker-options="timeSelectOptions"
                    @change="validTimePeriod"
                  ></el-time-select>
                </span>
                <span style="margin:0 20px;">至</span>
                <span class="my-picker-wrap">
                  <el-dropdown @command="v=>{handleDayCommand(item,v,'endIsNextday')}">
                    <span class="el-dropdown-link">
                      <el-button type="text">{{item.endIsNextday?'次日':'当日'}}</el-button>
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="false">当日</el-dropdown-item>
                      <el-dropdown-item :command="true">次日</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <el-time-select
                    v-model="item.endTime"
                    placeholder="结束时间"
                    value-format="HH:mm"
                    format="HH:mm"
                    :clearable="false"
                    :picker-options="timeSelectOptions"
                    @change="validTimePeriod"
                  ></el-time-select>
                </span>
                <el-button
                  v-if="inspectTimesList.length>1&&i>0"
                  icon="el-icon-minus"
                  circle
                  @click="handleDelInspectTimes(i)"
                  style="margin-left:20px;"
                ></el-button>
                <el-button
                  v-if="i==(inspectTimesList.length-1)"
                  icon="el-icon-plus"
                  circle
                  @click="handleAddInspectTimes"
                  style="margin-left:20px;"
                ></el-button>
              </el-form-item>
              <p v-if="timeValidTip" style="color:red;line-height:20px;padding:0 0 5px 30px;">{{timeValidTip}}</p>
              <el-form-item label-width="30px">
                <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> -->
                <el-checkbox-group v-model="checkedWeekDay" @change="handleCheckedWeekChange">
                  <el-checkbox label="1">周一</el-checkbox>
                  <el-checkbox label="2">周二</el-checkbox>
                  <el-checkbox label="3">周三</el-checkbox>
                  <el-checkbox label="4">周四</el-checkbox>
                  <el-checkbox label="5">周五</el-checkbox>
                  <el-checkbox label="6">周六</el-checkbox>
                  <el-checkbox label="7">周日</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>
            <template v-else-if="editForm.examineRate==1">
              <el-form-item label="开始时间：">
                <span class="my-picker-wrap">
                  <span class="is-today">当日</span>
                  <el-time-select
                    v-model="startTime"
                    placeholder="选择开始时间"
                    value-format="HH:mm"
                    format="HH:mm"
                    :clearable="false"
                    :picker-options="timeSelectOptions"
                    style="width:150px;"
                  ></el-time-select>
                </span>
              </el-form-item>
              <el-form-item label="结束时间：">
                <span class="my-picker-wrap">
                  <span class="is-today">{{Number(startTime.replace(':',''))>=Number(endTime.replace(':',''))?'次':'当'}}日</span>
                  <el-time-select
                    v-model="endTime"
                    placeholder="选择结束时间"
                    value-format="HH:mm"
                    format="HH:mm"
                    :clearable="false"
                    :picker-options="timeSelectOptions"
                    style="width:150px;"
                  ></el-time-select>
                </span>&nbsp;（可以跨天，但不可超过24小时）
              </el-form-item>
              <el-form-item label-width="40px">
                <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> -->
                <el-checkbox-group v-model="checkedWeekDay" @change="handleCheckedWeekChange">
                  <el-checkbox label="1">周一</el-checkbox>
                  <el-checkbox label="2">周二</el-checkbox>
                  <el-checkbox label="3">周三</el-checkbox>
                  <el-checkbox label="4">周四</el-checkbox>
                  <el-checkbox label="5">周五</el-checkbox>
                  <el-checkbox label="6">周六</el-checkbox>
                  <el-checkbox label="7">周日</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>
            <template v-else-if="editForm.examineRate==3">
              <el-form-item label="开始时间：">
                <el-input type="text" value="限周一" readonly style="width:100px;margin-right:10px;"></el-input>
                <el-time-select
                  v-model="startTime"
                  placeholder="请选择"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="timeSelectOptions"
                  :clearable="false"
                  style="width:120px;"
                ></el-time-select>
              </el-form-item>
              <el-form-item label="结束时间：">
                <el-select v-model="endWeekDay" placeholder="请选择" style="width:100px;margin-right:10px;">
                  <el-option v-for="(item,i) in ['一','二','三','四','五','六','日']" :key="i" :label="'周'+item" :value="i+1"></el-option>
                </el-select>
                <el-time-select
                  v-model="endTime"
                  placeholder="请选择"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="timeSelectOptions"
                  :clearable="false"
                  style="width:120px;"
                ></el-time-select>
              </el-form-item>
            </template>
            <template v-else-if="editForm.examineRate==4">
              <el-form-item label="开始时间：">
                <el-time-select
                  v-model="startTime"
                  placeholder="请选择"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="timeSelectOptions"
                  :clearable="false"
                  style="width:120px;"
                ></el-time-select>&nbsp;（限定月初1号开始）
              </el-form-item>
              <el-form-item label="结束时间：">
                <el-time-select
                  v-model="endTime"
                  placeholder="请选择"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="timeSelectOptions"
                  :clearable="false"
                  style="width:120px;"
                ></el-time-select>&nbsp;（限定月末结束）
              </el-form-item>
            </template>
            <template v-else-if="editForm.examineRate==5">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="开始时间：">
                    <el-time-select
                      v-model="startTime"
                      placeholder="请选择"
                      value-format="HH:mm"
                      format="HH:mm"
                      :picker-options="timeSelectOptions"
                      :clearable="false"
                      style="width:120px;"
                    ></el-time-select>
                    <p>限定按自然季度计算</p>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间：">
                    <el-time-select
                      v-model="endTime"
                      placeholder="请选择"
                      value-format="HH:mm"
                      format="HH:mm"
                      :picker-options="timeSelectOptions"
                      :clearable="false"
                      style="width:120px;"
                    ></el-time-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-card>
        </el-form-item>
        <p class="text-center" style="color:#999;">提示：计划创建后，无法再修改频率等众多信息。请核对无误后再保存。</p>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeDialog()">取消</el-button>
          <el-button type="primary" round @click="savePointType('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss">
.form-inspect-plan {
  .point-names {
    margin-top: 15px;
    color: #999;
    line-height: 20px;
  }
  .tree-select {
    width: 100% !important;
  }
  .el-form-item {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
  .formitem-point {
    .el-icon-circle-close {
      color: #000;
      font-size: 18px;
      &:hover {
        color: #000;
        font-size: 18px;
      }
    }
  }
  .my-picker-wrap {
    position: relative;
    display: inline-block;
    .el-date-editor {
      width: 150px;
    }
    .switch-today,
    .el-dropdown,
    .is-today {
      position: absolute;
      top: 0;
      left: 10px;
      z-index: 1;
    }
    .el-input__inner {
      padding-left: 80px;
    }
    .el-input__prefix {
      display: none;
    }
    .el-button--text {
      color: #606266;
      font-weight: normal;
    }
  }
  .el-card__body {
    padding-bottom: 0;
  }
}
</style>

<script>
import util from '@/utils/util'
import { getUsers } from '@/api/api'
import {
  getInspectPointNewList,
  addInspectPlan,
  getPointListOfPlan,
} from '@/api/inspectx'
import TreeSelect from '@/libs/TreeSelect/Main'
import { mapState, mapGetters } from 'vuex'
const weekOptions = ['1', '2', '3', '4', '5', '6', '7']

export default {
  name: 'InspectAreaForm',
  components: {
    TreeSelect,
  },
  props: {
    organizationId: {
      required: false,
    },
    editInfo: {
      type: Object,
      required: false,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
    labelList: Array,
  },
  computed: {
    ...mapState(['orgOptions', 'userinfo']),
    ...mapGetters(['isMuilUnitUser', 'userOrgId', 'userOrgIds']),
    // 点位是否跨单位
    isCrossPlatfrom() {
      if (!this.isMuilUnitUser || this.editForm.planPointsId.length <= 1)
        return false
      let nodes = this.checkedNodes
      return (
        nodes.filter((n) => {
          return n.data.orgId == nodes[0].data.orgId
        }).length != nodes.length
      )
    },
    // nodeOrgOptions() {
    //   let nodes = this.checkedNodes
    //   let arr = []
    //   if (this.isMuilUnitUser) {
    //     arr = [
    //       {
    //         id: this.userinfo.org.id,
    //         name: this.userinfo.org.name,
    //       },
    //     ]
    //   }
    //   if (nodes.length > 0 ) {
    //     arr.push({
    //       id: nodes[0].data.orgId,
    //       name: nodes[0].data.orgName,
    //     })
    //   }
    //   return arr
    // },
  },
  watch: {
    'editForm.lliableType'(val) {
      this.editForm.chargeManIds =
        this.isCrossPlatfrom && val == 1 ? [this.userinfo.org.id] : []
      this.getUserList()
    },
    checkedNodes(nodes) {
      let arr = []
      if (this.isMuilUnitUser) {
        arr = [
          {
            id: this.userinfo.org.id,
            name: this.userinfo.org.name,
          },
        ]
      }
      if (nodes.length > 0) {
        arr.push({
          id: nodes[0].data.orgId,
          name: nodes[0].data.orgName,
        })
      }
      this.nodeOrgOptions = arr
    },
  },
  data() {
    return {
      nodeOrgOptions: [],
      timeSelectOptions: {
        start: '00:00',
        step: '00:30',
        end: '23:30',
      },
      nodeProps: {
        multiple: true,
        lazy: true,
        lazyLoad: (node, resolve) => {
          if (node.data.leaf) {
            return resolve([])
          }
          getInspectPointNewList({
            orgIds: node.data.value,
            queryType: 0,
          }).then((res) => {
            resolve(
              res.data.map((n) => {
                return {
                  ...n,
                  value: n.id,
                  label: n.name,
                  leaf: true,
                }
              })
            )
          })
        },
      },
      nodeOptions: [],
      checkedNodes: [],
      pointNames: '',

      pickerOptions: $.extend(
        {
          disabledDate(time) {
            return time.getTime() <= new Date().setHours(0, 0, 0, 0) //不小于今天
          },
        },
        util.intDatePickerOptions(true)
      ),
      endDateOptions: {
        disabledDate(time) {
          return time.getTime() <= new Date().setHours(0, 0, 0, 0) //不小于今天
        },
      },
      buildList: [],
      util: util,

      checkedWeekDay: ['1', '2', '3', '4', '5', '6', '7'],
      checkAll: true,
      isIndeterminate: false,
      inspectTimesList: [
        {
          startTime: '09:00',
          endTime: '11:00',
          startIsNextday: false,
          endIsNextday: false,
        },
      ],
      timeValidTip: '',
      durationHours: 8,
      startTime: '09:00',
      startWeekDay: '限周一',
      endTime: '17:00',
      endWeekDay: 7,

      editForm: {
        id: '',
        orgId: '',
        name: '',
        startTimeStr: '',
        endTimeStr: '',
        examineRate: 2,
        labelId: '',
        lliableType: 1,
        planPointsId: [],
        chargeManIds: [],
      },
      editFormRules: {
        name: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
        startTimeStr: [
          {
            required: true,
            message: '请选择开始日期',
            trigger: 'change',
          },
        ],
        labelId: [{ required: true, message: '请选择标签' }],
        chargeManIds: [{ required: true, message: '请选择责任人' }],
        planPointsId: [{ required: true, message: '请选择点位' }],
      },
      userList: [],
      userLoading: false,
      tagList: [],
    }
  },
  created() {
    this.pointsChanged = false
    if (this.editInfo.id) {
      this.editForm = {
        ...this.editInfo,
        id: '',
        planPointsId: this.editInfo.planPointsId.split(','),
        startTimeStr: '',
        endTimeStr: '',
      }
      if (this.editInfo.startTime && this.editInfo.examineRate == 4) {
        let start =
          this.$moment(this.editInfo.startTime)
            .add(1, 'months')
            .format('yyyy-MM') + '-01'
        let end = this.$moment(start, 'yyyy-MM-DD')
          .endOf('month')
          .format('yyyy-MM-DD')
        this.editForm.startTimeStr = start
        this.editForm.endTimeStr = end
      }
      let rule = JSON.parse(this.editInfo.rule)
      if (this.editInfo.examineRate == 1) {
        this.startTime = rule.startTime
        this.endTime = rule.endTime
        this.checkedWeekDay = rule.workday.split(',')
      } else if (this.editInfo.examineRate == 2) {
        this.inspectTimesList = rule.workTime.map((n) => {
          n.endIsNextday = !!n.endIsNextday
          n.startIsNextday = !!n.startIsNextday
          return n
        })
        this.checkedWeekDay = rule.workday.split(',')
      } else if (this.editInfo.examineRate == 3) {
        this.startTime = rule.startTime
        this.endWeekDay = rule.endDay
        this.endTime = rule.endTime
      } else if (this.editInfo.examineRate == 4) {
        this.startTime = rule.startTime
        this.endTime = rule.endTime
      } else if (this.editInfo.examineRate == 5) {
        this.startTime = rule.startTime
        this.endTime = rule.endTime
      }
    }
    this.nodeOptions = this.orgOptions.map((n) => {
      return {
        value: n.organizationId,
        label: n.shortName,
        leaf: false,
      }
    })
  },
  mounted() {
    if (this.editInfo.id) {
      getPointListOfPlan({ ids: this.editInfo.planPointsId }).then((res) => {
        this.checkedNodes = res.data.map((n) => {
          return {
            data: {
              ...n,
              value: n.id,
              label: n.name,
            },
          }
        })
        this.pointNames = res.data
          .map((n) => {
            return n.name
          })
          .join(',')
        if (this.editForm.lliableType == 1) {
          this.editForm.chargeManIds = this.editInfo.lliableOrg
            .split('.')
            .map((n) => {
              return parseInt(n)
            })
          this.$refs.editForm.validateField('chargeManIds')
        }
        this.getUserList()
      })
    }
  },
  methods: {
    handleStartDateChange() {
      this.endDateOptions.disabledDate = (time) => {
        return time.getTime() <= new Date(this.editForm.startTimeStr).getTime()
      }
    },
    handleEndDateChange() {
      this.pickerOptions.disabledDate = (time) => {
        return (
          time.getTime() <= new Date().setHours(0, 0, 0, 0) ||
          time.getTime() > new Date(this.editForm.endTimeStr).getTime()
        )
      }
    },
    handleNodeChange(e) {
      if (e.length > 0) {
        this.pointsChanged = true
      }
      if (this.editInfo.id && !this.pointsChanged) {
        this.editForm.planPointsId = this.editInfo.planPointsId
      } else {
        let nodes = this.$refs.myCascader.getCheckedNodes() || []
        this.checkedNodes = nodes.filter((n) => {
          return n.data.leaf && !n.data.organizationId
        })
        this.$nextTick(() => {
          this.editForm.chargeManIds =
            this.isCrossPlatfrom && this.editForm.lliableType == 1
              ? [this.userinfo.org.id]
              : []
          this.$refs.editForm.validateField('chargeManIds')
          this.getUserList()
        })
      }
    },
    querySearch(queryString, cb) {
      var tagList = this.tagList
      var results = queryString
        ? tagList.filter(this.createFilter(queryString))
        : tagList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1
        )
      }
    },
    handleCheckedWeekChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === weekOptions.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < weekOptions.length
    },
    handleCheckAllChange(val) {
      this.checkedWeekDay = val ? weekOptions : []
      this.isIndeterminate = false
    },
    handleDelInspectTimes(i) {
      this.inspectTimesList.splice(i, 1)
      this.validTimePeriod()
    },
    handleAddInspectTimes() {
      let last = this.inspectTimesList[this.inspectTimesList.length - 1]
      let endHour = parseInt(last.endTime.substr(0, 2)) + 2
      this.inspectTimesList.push({
        startTime: last.endTime,
        endTime: `${endHour >= 24 ? endHour - 24 : endHour}:00`,
        startIsNextday: last.endIsNextday,
        endIsNextday: endHour >= 24 ? true : last.endIsNextday,
      })
      this.validTimePeriod()
    },
    getUserList() {
      if (this.editForm.lliableType == 1 || this.checkedNodes.length == 0) {
        this.userList = []
        return
      }
      this.userLoading = true
      getUsers({
        queryType: 0,
        orgIds: this.isCrossPlatfrom
          ? this.userinfo.org.id
          : this.checkedNodes[0].data.orgId,
      }).then((res) => {
        this.userList = res.data
        if (
          this.editInfo.id &&
          this.editInfo.lliableType == 2 &&
          (this.checkedNodes[0].data.orgId == this.editInfo.orgId ||
            (this.isCrossPlatfrom &&
              this.userinfo.org.id == this.editInfo.orgId))
        ) {
          this.$nextTick(() => {
            this.editForm.chargeManIds = this.editInfo.lliablepeoples.split(',')
          })
        }
        this.userLoading = false
      })
    },
    savePointType(formName) {
      if (!this.validTimePeriod()) return
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.editForm
          if (!this.validTimePeriod()) return
          if (this.isCurrentPeriod()) {
            let periodMap = {
              3: '周',
              4: '月',
              5: '季度',
            }
            this.$confirm(
              '是否生成本' + periodMap[this.editForm.examineRate] + '任务？',
              '提示',
              {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning',
                distinguishCancelAndClose: true,
              }
            )
              .then(() => {
                this.handleRequest(parames, 1)
              })
              .catch((action) => {
                if (action === 'cancel') {
                  this.handleRequest(parames, 0)
                }
              })
          } else {
            this.handleRequest(parames, 0)
          }
        }
      })
    },
    handleRequest(parames, isCreateTask) {
      let rule = {}
      let {
        name,
        labelId,
        lliableType,
        chargeManIds,
        examineRate,
        startTimeStr,
        endTimeStr,
      } = parames
      if (examineRate == 1) {
        rule = {
          startTime: this.startTime,
          endTime: this.endTime,
          workday: this.checkedWeekDay.join(','),
          endIsNextday:
            Number(this.endTime.replace(':', '')) <=
            Number(this.startTime.replace(':', ''))
              ? 1
              : 0,
        }
      } else if (examineRate == 2) {
        rule = {
          workTime: this.inspectTimesList.map((n) => {
            n.endIsNextday = n.endIsNextday ? 1 : 0
            n.startIsNextday = n.startIsNextday ? 1 : 0
            return n
          }),
          workday: this.checkedWeekDay.join(','),
        }
      } else if (examineRate == 3) {
        rule = {
          startDay: '1',
          startTime: this.startTime,
          endDay: this.endWeekDay,
          endTime: this.endTime,
        }
      } else if (examineRate == 4) {
        rule = {
          startTime: this.startTime,
          endTime: this.endTime,
        }
      } else if (examineRate == 5) {
        rule = {
          startTime: this.startTime,
          endTime: this.endTime,
        }
      }
      let planPointsId = this.checkedNodes
        .map((n) => {
          return n.data.value
        })
        .join(',')
      let newParam = {
        name,
        labelId,
        planPointsId,
        lliableType,
        lliableOrg: lliableType == 1 ? chargeManIds.join(',') : '',
        lliablepeoples: lliableType == 2 ? chargeManIds.join(',') : '',
        examineRate,
        startTimeStr,
        endTimeStr,
        createAccount: this.userinfo.accountName,
        updateAccount: this.userinfo.accountName,
        isCreateTask,
        rule: JSON.stringify(rule),
      }
      addInspectPlan(newParam).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success',
          })
        } else {
          this.$message.error(res.info)
        }
        this.closeDialog(true)
      })
    },
    validTimePeriod() {
      let isPass = true
      let list = this.inspectTimesList.map((n) => {
        return {
          ...n,
          startTimeNum:
            Number(n.startTime.replace(':', '')) +
            (n.startIsNextday ? 2400 : 0),
          endTimeNum:
            Number(n.endTime.replace(':', '')) + (n.endIsNextday ? 2400 : 0),
        }
      })
      let first = list[0]
      let times = 0
      let tip = ''
      for (var i = 0; i < list.length; i++) {
        let n = list[i]
        let startNext = n.startIsNextday ? '次日' : '当日'
        if (n.endTimeNum <= n.startTimeNum) {
          isPass = false
          tip = `第${i + 1}次巡检结束时间不能早于等于${startNext}${n.startTime}`
          break
        } else if (n.startTimeNum - first.startTimeNum > 2400) {
          isPass = false
          tip = `第${i + 1}次巡检开始时间不能晚于次日${first.startTime}`
          break
        } else if (n.endTimeNum - first.startTimeNum > 2400) {
          isPass = false
          tip = `第${i + 1}次巡检结束时间不能晚于次日${first.startTime}`
          break
        }
        if (i > 0) {
          if (n.startTimeNum < list[i - 1].endTimeNum) {
            let endNext = list[i - 1].endIsNextday ? '次日' : '当日'
            isPass = false
            tip = `第${i + 1}次巡检开始时间不能早于${endNext}${
              list[i - 1].endTime
            }`
            break
          }
        }
      }
      this.timeValidTip = isPass ? '' : tip
      return isPass
    },
    handleDayCommand(item, v, key) {
      item[key] = v
      this.validTimePeriod()
    },
    isCurrentPeriod() {
      let date = new Date()
      let startDateObj = new Date(this.editForm.startTimeStr)
      if (this.editForm.examineRate == 3) {
        let day = date.getDay()
        day = day > 0 ? day : 7
        let time = date.getTime()
        let beginTime = startDateObj.getTime()
        if (beginTime - time < (8 - day) * 24 * 60 * 60000) {
          return true
        }
      } else if (this.editForm.examineRate == 4) {
        if (
          date.getFullYear() == startDateObj.getFullYear() &&
          date.getMonth() == startDateObj.getMonth()
        ) {
          return true
        }
      } else if (this.editForm.examineRate == 5) {
        if (
          date.getFullYear() === startDateObj.getFullYear() &&
          Math.ceil((date.getMonth() + 1) / 3) ===
            Math.ceil((startDateObj.getMonth() + 1) / 3)
        ) {
          return true
        }
      }
      return false
    },
  },
}
</script>